using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.USDK;
using NetProtocol.POD;
using System;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class SDKModule : Singleton<SDKModule>
    {
        private SDKModule() { }
        /// <summary>
        /// 准备继续登录的用户信息
        /// </summary>
        private UserInfo continueLoginUserInfo;

        /// <summary>
        /// 初始化SDK
        /// </summary>
        /// <returns></returns>
        public UniTask<bool> InitSDK()
        {
            if (!ManagerCenter.ProjectSetting.IsSDKMode())
            {
                return UniTask.FromResult(true);
            }

            AutoResetUniTaskCompletionSource<bool> autoResetUniTaskCompletionSource = AutoResetUniTaskCompletionSource<bool>.Create();
            IQIUSDK.Instance.OnInitFailed = (msg) =>
            {
                Debug.LogError($"SDK Init Fail msg = {msg}");
                autoResetUniTaskCompletionSource.TrySetResult(false);
            };

            IQIUSDK.Instance.OnInitSuccess = () =>
            {
                Debug.Log("SDK Init Success");
                InitSDKCallBack();
                autoResetUniTaskCompletionSource.TrySetResult(true);
            };
            IQIUSDK.Instance.init();
            return autoResetUniTaskCompletionSource.Task;
        }

        /// <summary>
        /// 初始化sdk回调, 业务上也可以自定义覆盖
        /// </summary>
        private void InitSDKCallBack()
        {
            IQIUSDK.Instance.OnLoginSuccess = (userInfo) => OnSDKUserLogin(userInfo).Forget();
            IQIUSDK.Instance.OnLoginFailed = (msg) =>
            {
                Debug.LogWarning($"SDK OnLoginFailed msg = {msg}");
                NoticeModule.ShowNotice(NoticeConstant.ID_ON_SDK_LOGIN_FAIL, () =>
                {
                    IQIUSDK.Instance.login();
                }, null, null, msg);
            };
            IQIUSDK.Instance.OnLoginCancel = () =>
            {
                //TODO:点击后重新拉起
                Debug.LogWarning($"SDK OnLoginCancel");
                IQIUSDK.Instance.login();
            };

            IQIUSDK.Instance.OnSwitchSuccess = async (userInfo) =>
            {
                await GameServerModule.NetCore.CS_logout();
                OnSDKUserLogin(userInfo).Forget();
            };
            IQIUSDK.Instance.OnSwitchFailed = (msg) =>
            {
                Debug.LogError($"SDK OnSwitchFailed msg = {msg}");
                NoticeModule.ShowNoticeNoCall(NoticeConstant.ID_ON_SDK_SWITCH_FAIL, msg);
            };
            IQIUSDK.Instance.OnSwitchCancel = () =>
            {
                Debug.LogWarning($"SDK OnSwitchCancel");
            };

            IQIUSDK.Instance.OnLogoutSuccess = async () =>
            {
                await GameServerModule.NetCore.CS_logout();
                ProcedureFSM.Instance.ChangeState<ProcedureReset>();
            };
            IQIUSDK.Instance.OnLogoutFailed = (msg) =>
            {
                Debug.LogError($"SDK OnLogoutFailed msg = {msg}");
                NoticeModule.ShowNoticeNoCall(NoticeConstant.ID_ON_SDK_LOGOUT_FAIL, msg);
            };
            IQIUSDK.Instance.OnLogoutCancel = () =>
            {
                Debug.LogWarning($"SDK OnLogoutCancel");
            };

            IQIUSDK.Instance.OnExitSuccess = async () =>
            {
                RoleInfo roleInfo = GetRoleInfo();
                if (roleInfo != null)
                {
                    IQIUSDK.Instance.roleExitGame(roleInfo);
                }
                await GameServerModule.NetCore.CS_logout();
                await UniTask.Delay(500);
                Application.Quit();
#if UNITY_EDITOR
                EditorApplication.ExitPlaymode();
#endif
            };
            IQIUSDK.Instance.OnExitFailed = (msg) =>
            {
                Debug.LogError($"SDK OnExitFailed msg = {msg}");
            };
            IQIUSDK.Instance.OnExitCancel = () =>
            {
                Debug.LogWarning($"SDK OnExitCancel");
            };

            IQIUSDK.Instance.OnPaySuccess = (data) =>
            {
                Debug.LogWarning($"SDK OnPaySuccess orderId = {data.cpOrderId}");
            };
            IQIUSDK.Instance.OnPayFailed = (data) =>
            {
                Debug.LogError($"SDK OnPayFailed msg = {data.msg}");
                NoticeModule.ShowNoticeNoCall(NoticeConstant.ID_ON_SDK_PAY_FAIL, data.msg);
            };
            IQIUSDK.Instance.OnPayCancel = (data) =>
            {
                Debug.LogWarning($"SDK OnPayCancel");
            };
        }

        private async UniTaskVoid OnSDKUserLogin(UserInfo userInfo)
        {
            if (ProcedureFSM.Instance.current.GetType() == typeof(ProcedureLogin))
            {
                continueLoginUserInfo = null;
                MsgDispatcher.Broadcast(MsgEventType.SDK_LOGIN_SUCCESS, userInfo);
            }
            else
            {
                continueLoginUserInfo = userInfo;
                await GameServerModule.NetCore.CS_logout();
                ProcedureFSM.Instance.ChangeState<ProcedureReset>();
            }
        }

        /// <summary>
        /// 开始登录
        /// </summary>
        public void StartLogin()
        {
            if (continueLoginUserInfo == null)
            {
                IQIUSDK.Instance.login();
            }
            else
            {
                OnSDKUserLogin(continueLoginUserInfo).Forget();
            }
        }

        /// <summary>
        /// 返回sdk的roleInfo对象,
        /// </summary>
        /// <returns></returns>
        public RoleInfo GetRoleInfo()
        {
            if (GameDataCenter.PlayerData == null)
            {
                return null;
            }
            RoleInfo roleInfo = CreateDefaultRole();
            roleInfo.roleId = GameDataCenter.PlayerData.pid + "";
            roleInfo.roleName = GameDataCenter.PlayerData.playerName;
            roleInfo.roleLevel = GameDataCenter.PlayerData.level + "";
            roleInfo.roleCreateTime = GameDataCenter.PlayerData.createTime;
            roleInfo.timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            return roleInfo;
        }

        public RoleInfo GetNewRoleInfo(RoleInfoPOD roleInfoPOD)
        {
            RoleInfo roleInfo = CreateDefaultRole();
            roleInfo.roleId = roleInfoPOD.pid + "";
            roleInfo.roleName = roleInfoPOD.playerName;
            roleInfo.roleLevel = roleInfoPOD.level.ToString();
            roleInfo.roleCreateTime = roleInfoPOD.createTime;
            roleInfo.timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            return roleInfo;
        }

        public RoleInfo CreateDefaultRole()
        {
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.roleId = "";
            roleInfo.roleName = "";
            roleInfo.serverId = GameDataCenter.CurrGameServerInfo.areaId;
            roleInfo.serverName = GameDataCenter.CurrGameServerInfo.areaName;
            roleInfo.roleLevel = "0";
            roleInfo.vipLevel = "0";
            roleInfo.rolePower = "0";
            roleInfo.roleBalance = "0";
            roleInfo.roleCreateTime = 0L;
            roleInfo.timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            return roleInfo;
        }

    }

}
